package com.oriole.api.config.security.local;

import com.oriole.common.constant.Constants;
import com.oriole.common.util.FastJsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/15 0:13
 * description: 解析出头中的token
 */
@Component
@ConditionalOnProperty(prefix = "oriole", name = "login-type", havingValue = "local")
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(Constants.HEADER_STRING);
        if (StringUtils.isNotBlank(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            String realToken = token.replace(Constants.TOKEN_PREFIX, "");
            TokenProvider tokenProvider = new TokenProvider();
            Object principal = tokenProvider.getToken(realToken, Constants.JWT_PRINCIPAL);
            Object authoritiesStr = tokenProvider.getToken(realToken, Constants.JWT_AUTHORITIES);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            if (authoritiesStr instanceof Collection) {
                authorities = FastJsonUtil.parseArray(FastJsonUtil.toJsonString(authoritiesStr), SimpleGrantedAuthority.class);
            }
            if (!ObjectUtils.isEmpty(principal)) {
                OrioleUsernamePasswordAuthenticationToken authenticationToken = new OrioleUsernamePasswordAuthenticationToken(principal, realToken, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
